<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'数据库'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-form-item label="数据库类型" prop="connectionConfig.dbType">
            <el-select
              v-model="formData.connectionConfig.dbType"
              placeholder="请选择数据库类型"
              style="width: 100%"
              @change="handleDbTypeChange"
            >
              <el-option label="MySQL" value="mysql" />
              <el-option label="Oracle" value="oracle" />
              <el-option label="SQL Server" value="sqlserver" />
              <el-option label="PostgreSQL" value="postgresql" />
              <el-option label="MongoDB" value="mongodb" />
              <el-option label="Redis" value="redis" />
            </el-select>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="服务器地址" prop="connectionConfig.host">
                <el-input v-model="formData.connectionConfig.host" placeholder="请输入数据库服务器地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口" prop="connectionConfig.port">
                <el-input-number
                  v-model="formData.connectionConfig.port"
                  :min="1"
                  :max="65535"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="connectionConfig.username">
                <el-input v-model="formData.connectionConfig.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="connectionConfig.password">
                <el-input
                  v-model="formData.connectionConfig.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="数据库名称" prop="connectionConfig.database">
            <el-input v-model="formData.connectionConfig.database" placeholder="请输入数据库名称" />
          </el-form-item>

          <el-form-item label="连接参数" prop="connectionConfig.params">
            <el-button
              type="primary"
              size="small"
              @click="addParam"
              style="margin-bottom: 10px"
            >
              添加连接参数
            </el-button>
            <el-table
              :data="formData.connectionConfig.params"
              border
              style="width: 100%"
              empty-text="暂无连接参数"
            >
              <el-table-column prop="key" label="参数名" width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.key"
                    placeholder="例如: charset"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="value" label="参数值">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.value"
                    placeholder="例如: utf8mb4"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeParam($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="连接池配置">
            <el-switch v-model="formData.connectionConfig.pool.enabled" active-text="启用连接池" />
          </el-form-item>

          <template v-if="formData.connectionConfig.pool.enabled">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大连接数" prop="connectionConfig.pool.max">
                  <el-input-number
                    v-model="formData.connectionConfig.pool.max"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最小连接数" prop="connectionConfig.pool.min">
                  <el-input-number
                    v-model="formData.connectionConfig.pool.min"
                    :min="0"
                    :max="formData.connectionConfig.pool.max"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="获取连接超时(ms)" prop="connectionConfig.pool.acquireTimeout">
                  <el-input-number
                    v-model="formData.connectionConfig.pool.acquireTimeout"
                    :min="1000"
                    :max="30000"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="连接空闲超时(ms)" prop="connectionConfig.pool.idleTimeout">
                  <el-input-number
                    v-model="formData.connectionConfig.pool.idleTimeout"
                    :min="10000"
                    :max="600000"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-tab-pane>

        <!-- 采集配置 -->
        <el-tab-pane label="采集配置" name="collection">
          <el-form-item label="采集模式" prop="collectionConfig.mode">
            <el-radio-group v-model="formData.collectionConfig.mode">
              <el-radio label="table">表采集</el-radio>
              <el-radio label="sql">SQL采集</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="formData.collectionConfig.mode === 'table'">
            <el-form-item label="采集表" prop="collectionConfig.tables">
              <el-button
                type="primary"
                size="small"
                @click="addTable"
                style="margin-bottom: 10px"
              >
                添加采集表
              </el-button>
              <el-table
                :data="formData.collectionConfig.tables"
                border
                style="width: 100%"
                empty-text="暂无采集表配置"
              >
                <el-table-column prop="tableName" label="表名" width="200">
                  <template #default="{ row, $index }">
                    <el-input
                      v-model="row.tableName"
                      placeholder="例如: user_info"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="columns" label="采集字段">
                  <template #default="{ row, $index }">
                    <el-select
                      v-model="row.columns"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      style="width: 100%"
                      placeholder="选择或输入字段名(留空表示所有字段)"
                    >
                      <el-option
                        v-for="col in getTableColumns(row.tableName)"
                        :key="col"
                        :label="col"
                        :value="col"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="where" label="条件">
                  <template #default="{ row, $index }">
                    <el-input
                      v-model="row.where"
                      placeholder="例如: create_time > '2023-01-01'"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeTable($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item label="SQL语句" prop="collectionConfig.sql">
              <el-input
                v-model="formData.collectionConfig.sql"
                type="textarea"
                :rows="5"
                placeholder="请输入采集SQL，例如: SELECT * FROM user WHERE status = 1"
              />
            </el-form-item>
          </template>

          <el-form-item label="增量采集" prop="collectionConfig.incremental">
            <el-switch v-model="formData.collectionConfig.incremental" />
          </el-form-item>

          <template v-if="formData.collectionConfig.incremental">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="增量字段" prop="collectionConfig.incrementalField">
                  <el-input
                    v-model="formData.collectionConfig.incrementalField"
                    placeholder="例如: update_time"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="初始值" prop="collectionConfig.incrementalStartValue">
                  <el-input
                    v-model="formData.collectionConfig.incrementalStartValue"
                    placeholder="例如: 2023-01-01 00:00:00"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <el-form-item label="采集频率" prop="collectionConfig.cron">
            <el-select
              v-model="formData.collectionConfig.cron"
              placeholder="请选择采集频率"
              style="width: 100%"
            >
              <el-option label="每分钟" value="0 * * * * ?" />
              <el-option label="每5分钟" value="0 */5 * * * ?" />
              <el-option label="每小时" value="0 0 * * * ?" />
              <el-option label="每天0点" value="0 0 0 * * ?" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>

          <template v-if="formData.collectionConfig.cron === 'custom'">
            <el-form-item label="CRON表达式" prop="collectionConfig.customCron">
              <el-input
                v-model="formData.collectionConfig.customCron"
                placeholder="请输入CRON表达式"
              />
              <span class="el-form-item__tip">例如: 0 0/30 * * * ? 表示每30分钟执行一次</span>
            </el-form-item>
          </template>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-form-item label="批量大小" prop="advancedConfig.batchSize">
            <el-input-number
              v-model="formData.advancedConfig.batchSize"
              :min="1"
              :max="10000"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">每次从数据库读取的记录数</span>
          </el-form-item>

          <el-form-item label="超时设置(秒)" prop="advancedConfig.timeout">
            <el-input-number
              v-model="formData.advancedConfig.timeout"
              :min="1"
              :max="3600"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="错误处理" prop="advancedConfig.errorHandling">
            <el-select
              v-model="formData.advancedConfig.errorHandling"
              placeholder="请选择错误处理策略"
              style="width: 100%"
            >
              <el-option label="跳过错误继续执行" value="skip" />
              <el-option label="停止采集并报错" value="stop" />
              <el-option label="重试3次后跳过" value="retry" />
            </el-select>
          </el-form-item>

          <el-form-item label="数据转换" prop="advancedConfig.transformScript">
            <el-input
              v-model="formData.advancedConfig.transformScript"
              type="textarea"
              :rows="5"
              placeholder="可输入JavaScript脚本对采集数据进行转换"
            />
            <span class="el-form-item__tip">可选，例如: return { ...row, processed: true }</span>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditDatabaseDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit', 'test-connection'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑数据库采集配置' : '新增数据库采集配置'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      connectionConfig: {
        dbType: 'mysql',
        host: 'localhost',
        port: 3306,
        username: '',
        password: '',
        database: '',
        params: [],
        pool: {
          enabled: true,
          max: 10,
          min: 1,
          acquireTimeout: 10000,
          idleTimeout: 60000
        }
      },
      collectionConfig: {
        mode: 'table',
        tables: [],
        sql: '',
        incremental: false,
        incrementalField: '',
        incrementalStartValue: '',
        cron: '0 * * * * ?',
        customCron: ''
      },
      advancedConfig: {
        batchSize: 1000,
        timeout: 30,
        errorHandling: 'skip',
        transformScript: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'connectionConfig.dbType': [
        { required: true, message: '请选择数据库类型', trigger: 'change' }
      ],
      'connectionConfig.host': [
        { required: true, message: '请输入服务器地址', trigger: 'blur' }
      ],
      'connectionConfig.port': [
        { required: true, message: '请输入端口号', trigger: 'blur' }
      ],
      'connectionConfig.database': [
        { required: true, message: '请输入数据库名称', trigger: 'blur' }
      ],
      'collectionConfig.tables': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.collectionConfig.mode === 'table' && (!value || value.length === 0)) {
              return callback(new Error('至少需要配置一个采集表'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      'collectionConfig.sql': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.collectionConfig.mode === 'sql' && !value) {
              return callback(new Error('请输入SQL语句'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'collectionConfig.incrementalField': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.collectionConfig.incremental && !value) {
              return callback(new Error('请输入增量字段'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ]
    }

    // 添加连接参数
    const addParam = () => {
      formData.value.connectionConfig.params.push({
        key: '',
        value: ''
      })
    }

    // 删除连接参数
    const removeParam = (index) => {
      formData.value.connectionConfig.params.splice(index, 1)
    }

    // 添加采集表
    const addTable = () => {
      formData.value.collectionConfig.tables.push({
        tableName: '',
        columns: [],
        where: ''
      })
    }

    // 删除采集表
    const removeTable = (index) => {
      formData.value.collectionConfig.tables.splice(index, 1)
    }

    // 获取表字段（模拟方法，实际应从后端获取）
    const getTableColumns = (tableName) => {
      if (!tableName) return []
      // 这里应该是从后端获取表字段的API调用
      // 模拟返回一些字段
      return ['id', 'name', 'create_time', 'update_time']
    }

    // 处理数据库类型变化
    const handleDbTypeChange = (type) => {
      // 根据不同类型设置默认端口
      const defaultPorts = {
        mysql: 3306,
        oracle: 1521,
        sqlserver: 1433,
        postgresql: 5432,
        mongodb: 27017,
        redis: 6379
      }
      formData.value.connectionConfig.port = defaultPorts[type] || 3306
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 测试连接
    const testConnection = async () => {
      try {
        await formRef.value.validateField(['connectionConfig.dbType', 'connectionConfig.host', 'connectionConfig.port', 'connectionConfig.username', 'connectionConfig.database'])
        
        emit('test-connection', {
          dbType: formData.value.connectionConfig.dbType,
          host: formData.value.connectionConfig.host,
          port: formData.value.connectionConfig.port,
          username: formData.value.connectionConfig.username,
          password: formData.value.connectionConfig.password,
          database: formData.value.connectionConfig.database,
          params: formData.value.connectionConfig.params
        })
      } catch (error) {
        console.error('连接测试验证失败:', error)
        ElMessage.error('请检查连接配置是否正确')
      }
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理自定义CRON表达式
        const finalData = JSON.parse(JSON.stringify(formData.value))
        if (finalData.collectionConfig.cron === 'custom') {
          finalData.collectionConfig.cron = finalData.collectionConfig.customCron
        }
        delete finalData.collectionConfig.customCron
        
        // 过滤空参数
        finalData.connectionConfig.params = finalData.connectionConfig.params
          .filter(param => param.key && param.value)
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          connectionConfig: {
            ...defaultFormData.connectionConfig,
            ...(newVal.connectionConfig || {}),
            pool: {
              ...defaultFormData.connectionConfig.pool,
              ...(newVal.connectionConfig?.pool || {})
            }
          },
          collectionConfig: {
            ...defaultFormData.collectionConfig,
            ...(newVal.collectionConfig || {})
          },
          advancedConfig: {
            ...defaultFormData.advancedConfig,
            ...(newVal.advancedConfig || {})
          }
        }))
        
        // 处理自定义CRON表达式
        if (newVal.collectionConfig?.cron && 
            !['0 * * * * ?', '0 */5 * * * ?', '0 0 * * * ?', '0 0 0 * * ?'].includes(newVal.collectionConfig.cron)) {
          formData.value.collectionConfig.cron = 'custom'
          formData.value.collectionConfig.customCron = newVal.collectionConfig.cron
        }
        
        // 确保params和tables是数组
        if (!Array.isArray(formData.value.connectionConfig.params)) {
          formData.value.connectionConfig.params = []
        }
        if (!Array.isArray(formData.value.collectionConfig.tables)) {
          formData.value.collectionConfig.tables = []
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      addParam,
      removeParam,
      addTable,
      removeTable,
      getTableColumns,
      handleDbTypeChange,
      testConnection,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>